package www.woniuxy.com.class112.service.impl;

import cn.hutool.core.bean.BeanUtil;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;
import www.woniuxy.com.class112.dao.KnowledgeBaseMapper;
import www.woniuxy.com.class112.dto.KnowledgeBaseDto;
import www.woniuxy.com.class112.entity.KnowledgeBase;

import www.woniuxy.com.class112.entity.Qus;
import www.woniuxy.com.class112.param.KnowledgeBasePageParam;
import www.woniuxy.com.class112.param.QusParam;
import www.woniuxy.com.class112.service.KnowledgeBaseService;

import javax.annotation.Resource;

import java.util.Date;
import java.util.List;

@Service
public class KnowledgeBaseServiceImpl implements KnowledgeBaseService {
    @Resource
    private ElasticsearchRestTemplate esTemplate;
    @Resource
    private KnowledgeBaseMapper knowledgeBaseMapper;
    @Override
    public void addKnowledgeBase(QusParam param) {
        KnowledgeBase knowledgeBase = BeanUtil.toBean(param, KnowledgeBase.class);
        knowledgeBase.setAuthorId(param.getUserId());
        knowledgeBase.setCreatedTime(new Date());
        knowledgeBaseMapper.insert(knowledgeBase);
        Qus qus = BeanUtil.toBean(param, Qus.class);
        qus.setKnowledge_id(knowledgeBase.getKnowledgeId());
        esTemplate.save(qus);
    }

    @Override
    public PageInfo<KnowledgeBaseDto> queryKnowledgeBase(KnowledgeBasePageParam param) {
        PageHelper.startPage(param.getPageIndex() == null ? 1 : param.getPageIndex(), param.getPageSize() == null ? 1 : param.getPageSize());
//        List<KnowledgeBase> knowledgeBases = knowledgeBaseMapper.queryKnowledgeBase(param.getTitle(), param.getCategoryId());
//        for (KnowledgeBase knowledgeBase : knowledgeBases) {
//            System.out.println(knowledgeBase);
//        }
//        PageInfo<KnowledgeBase> knowledgeBasePageInfo = new PageInfo<>(knowledgeBases);
        List<KnowledgeBaseDto> knowledgeBaseDtos = knowledgeBaseMapper.queryKnowledgeBases(param.getTitle(), param.getCategoryId());
        return new PageInfo<>(knowledgeBaseDtos);
    }

    @Override
    public void deleteKnowledgeBase(Long knowledgeId) {
        knowledgeBaseMapper.deleteByPrimaryKey(knowledgeId);
        Qus qus = new Qus();
        qus.setKnowledge_id(knowledgeId);
        esTemplate.delete(qus);
    }

    @Override
    public KnowledgeBase sss(Long id) {
        KnowledgeBase knowledgeBase = knowledgeBaseMapper.selectByPrimaryKey(id);
        return knowledgeBase;
    }

    @Override
    public void compileKnowledgeBase(KnowledgeBase form) {
        KnowledgeBase knowledgeBase = knowledgeBaseMapper.selectByPrimaryKey(form.getKnowledgeId());
        if (knowledgeBase==null){
            throw new RuntimeException("知识库不存在");
        }
        knowledgeBaseMapper.updateByPrimaryKeySelective(form);
    }
}
